package com.bnzj.cloud.business.core.persistence.repository;

import java.util.List;
import java.util.Set;

import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.bnzj.cloud.business.core.persistence.entity.SysDepartment;
import com.bnzj.core.persistence.repository.BaseRepository;

@Repository
public interface SysDepartmentRepository extends BaseRepository<SysDepartment, Long>{

	 @Query(value ="select d.*, "
	     + "(select if(count(1) > 0, 1, 0) from bnz_sys_department e where e.enabled = ?1 and d.id = e.pid) as child_num "
	     + "from bnz_sys_department d where 1=1 and d.enabled = ?1 and d.pid = ?2", nativeQuery = true)
    List<SysDepartment> findAllByEnabledAndPid(Boolean enabled, Long id);

    List<SysDepartment> findAllByEnabled(Boolean enabled, Sort sort);

    /**
     * 查询启用的部门Id
     */
    @Query("select id from #{#entityName} where enabled = 1")
    Set<Long> findAllIdByEnabled();
    
    @Modifying
    @Query("update #{#entityName} set enabled = 0 where id in (?1)")
    int disable(List<Long> id);

    @Modifying
    @Query(value = "insert into bnz_sys_department(id) value (?1)", nativeQuery = true)
    void insertId(Long id);   

    @Query(value = "update #{#entityName} set enabled = 0 where id = ?1",nativeQuery = true)
    void deleteById(Long id);
}
